import { initParticlesJS } from '../particles.js';

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function () {
    // 粒子效果
    initParticlesJS();
    // 更新购物车数量
    updateCartCount();

    // 初始化表单切换
    initFormSwitching();

    // 初始化表单验证和提交
    initFormValidation();

    // 初始化密码显示切换
    initPasswordToggle();

    // 移动菜单切换
    document.getElementById('mobile-menu-btn').addEventListener('click', function () {
        const mobileMenu = document.getElementById('mobile-menu');
        if (mobileMenu.classList.contains('hidden')) {
            mobileMenu.classList.remove('hidden');
        } else {
            mobileMenu.classList.add('hidden');
        }
    });
});

// 更新购物车数量
function updateCartCount() {
    const cart = localStorage.getItem('cart') ? JSON.parse(localStorage.getItem('cart')) : [];
    const cartCount = document.getElementById('cart-count');
    cartCount.textContent = cart.length;
}

// 初始化表单切换
function initFormSwitching() {
    const loginTab = document.getElementById('login-tab');
    const registerTab = document.getElementById('register-tab');
    const loginForm = document.getElementById('login-form');
    const registerForm = document.getElementById('register-form');
    const switchToRegister = document.getElementById('switch-to-register');
    const switchToLogin = document.getElementById('switch-to-login');

    loginTab.addEventListener('click', function () {
        loginTab.classList.add('border-b-2', 'border-blue-500', 'text-blue-600');
        loginTab.classList.remove('text-gray-500');
        registerTab.classList.remove('border-b-2', 'border-blue-500', 'text-blue-600');
        registerTab.classList.add('text-gray-500');
        loginForm.classList.remove('hidden');
        registerForm.classList.add('hidden');
    });

    registerTab.addEventListener('click', function () {
        registerTab.classList.add('border-b-2', 'border-blue-500', 'text-blue-600');
        registerTab.classList.remove('text-gray-500');
        loginTab.classList.remove('border-b-2', 'border-blue-500', 'text-blue-600');
        loginTab.classList.add('text-gray-500');
        registerForm.classList.remove('hidden');
        loginForm.classList.add('hidden');
    });

    switchToRegister.addEventListener('click', function (e) {
        e.preventDefault();
        registerTab.click();
    });

    switchToLogin.addEventListener('click', function (e) {
        e.preventDefault();
        loginTab.click();
    });
}

// 初始化表单验证和提交
function initFormValidation() {
    // 登录表单验证和提交
    const loginButton = document.getElementById('login-button');
    loginButton.addEventListener('click', function () {
        const username = document.getElementById('login-username').value.trim();
        const password = document.getElementById('login-password').value.trim();
        const usernameError = document.getElementById('login-username-error');
        const passwordError = document.getElementById('login-password-error');
        let isValid = true;

        // 验证用户名
        if (!username) {
            usernameError.textContent = '请输入用户名';
            usernameError.classList.remove('hidden');
            isValid = false;
        } else {
            usernameError.classList.add('hidden');
        }

        // 验证密码
        if (!password) {
            passwordError.textContent = '请输入密码';
            passwordError.classList.remove('hidden');
            isValid = false;
        } else {
            passwordError.classList.add('hidden');
        }

        // 如果验证通过，尝试登录
        if (isValid) {
            fetch('http://localhost:3000/api/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    'username': username,
                    'passwordHash': password
                }),
                credentials: 'include' // 携带凭证
            })
            .then(response => {
                console.log('response', response.status);
                return response.json();
            })
            .then(data => {
                if (data.code === 200) {
                    // 检查 data.user 是否存在
                    if (data.data && data.data.user) {
                        console.log('登录成功:', data.data.user);

                        // 获取用户的 accountId
                        const accountId = data.data.user.accountId;

                        // 调用获取个人信息的接口
                        fetch(`http://localhost:3000/api/getUserInfoByAccountId?accountId=${accountId}`, {
                            method: 'GET',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            credentials: 'include' // 携带凭证
                        })
                        .then(userInfoResponse => userInfoResponse.json())
                        .then(userInfoData => {
                            if (userInfoData.code === 200) {
                                // 合并登录信息和个人信息
                                const user = {
                                    ...data.data.user,
                                    ...userInfoData.data
                                };

                                // 保存当前用户到 localStorage
                                localStorage.setItem('currentUser', JSON.stringify(user));

                                // 获取 IP 地址
                                fetch('https://api.ipify.org?format=json')
                                .then(ipResponse => ipResponse.json())
                                .then(ipData => {
                                    const ip = ipData.ip;
                                    // 使用高德 API 根据 IP 地址获取定位信息
                                    const amapKey = 'aa40a1d28dcb61b07f91f246b65592d9'; // 替换为你的高德 API Key
                                    fetch(`https://restapi.amap.com/v3/ip?ip=${ip}&output=json&key=${amapKey}`)
                                    .then(amapResponse => amapResponse.json())
                                    .then(amapData => {
                                        if (amapData.status === '1') {
                                            const { province, city, adcode } = amapData;
                                            console.log('定位信息:', province, city, adcode);
                                            // 可以将定位信息保存到 localStorage 或进行其他操作
                                            localStorage.setItem('location', JSON.stringify({ province, city, adcode }));
                                        } else {
                                            console.error('高德 API 获取定位信息失败:', amapData.info);
                                        }
                                    })
                                    .catch(amapError => {
                                        console.error('高德 API 请求出错:', amapError);
                                    });
                                })
                                .catch(ipError => {
                                    console.error('获取 IP 地址出错:', ipError);
                                });

                                try {
                                    // 显示成功通知
                                    showNotification('登录成功，即将跳转到首页');

                                    // 2 秒后跳转到首页
                                    setTimeout(function () {
                                        window.location.href = 'index.html';
                                    }, 2000);
                                } catch (error) {
                                    console.log('解析用户信息出错：', error);
                                }
                            } else {
                                // 显示错误信息
                                passwordError.textContent = userInfoData.message;
                                passwordError.classList.remove('hidden');
                            }
                        })
                        .catch(error => {
                            console.error('获取个人信息请求出错:', error);
                            passwordError.textContent = '获取个人信息请求出错，请稍后再试';
                            passwordError.classList.remove('hidden');
                        });
                    } else {
                        console.error('登录响应中缺少 user 对象');
                        passwordError.textContent = '登录响应数据格式错误，请稍后再试';
                        passwordError.classList.remove('hidden');
                    }
                } else {
                    // 显示错误信息
                    passwordError.textContent = data.message;
                    passwordError.classList.remove('hidden');
                }
            })
            .catch(error => {
                console.error('登录请求出错:', error);
                passwordError.textContent = '登录请求出错，请稍后再试';
                passwordError.classList.remove('hidden');
            });
        }
    });

    // 注册表单验证和提交
    const registerButton = document.getElementById('register-button');
    registerButton.addEventListener('click', function () {
        const username = document.getElementById('register-username').value.trim();
        const email = document.getElementById('register-email').value.trim();
        const password = document.getElementById('register-password').value.trim();
        const confirmPassword = document.getElementById('register-confirm-password').value.trim();
        const terms = document.getElementById('terms').checked;

        const usernameError = document.getElementById('register-username-error');
        const emailError = document.getElementById('register-email-error');
        const passwordError = document.getElementById('register-password-error');
        const confirmPasswordError = document.getElementById('register-confirm-password-error');
        const termsError = document.getElementById('terms-error');

        let isValid = true;

        // 验证用户名
        if (!username || username.length < 3) {
            usernameError.textContent = '用户名至少需要3个字符';
            usernameError.classList.remove('hidden');
            isValid = false;
        } else {
            usernameError.classList.add('hidden');
        }

        // 验证邮箱
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!email || !emailRegex.test(email)) {
            emailError.textContent = '请输入有效的电子邮箱';
            emailError.classList.remove('hidden');
            isValid = false;
        } else {
            emailError.classList.add('hidden');
        }

        // 验证密码
        if (!password || password.length < 6) {
            passwordError.textContent = '密码至少需要6个字符';
            passwordError.classList.remove('hidden');
            isValid = false;
        } else {
            passwordError.classList.add('hidden');
        }

        // 验证确认密码
        if (password !== confirmPassword) {
            confirmPasswordError.textContent = '两次输入的密码不一致';
            confirmPasswordError.classList.remove('hidden');
            isValid = false;
        } else {
            confirmPasswordError.classList.add('hidden');
        }

        // 验证用户协议
        if (!terms) {
            termsError.textContent = '请同意用户协议和隐私政策';
            termsError.classList.remove('hidden');
            isValid = false;
        } else {
            termsError.classList.add('hidden');
        }

        // 如果验证通过，发送注册请求
        if (isValid) {
            const newUser = {
                username: username,
                email: email,
                password: password,
                registrationDate: new Date().toISOString(),
                avatar: `https://picsum.photos/id/${Math.floor(Math.random() * 100)}/200/200`
            };

            fetch('http://localhost:8080/register', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(newUser),
                credentials: 'include' // 携带凭证
            })
            .then(response => {
                console.log('response', response.status);
                return response.json();
            })
            .then(data => {
                if (data.code === 200) {
                    // 保存当前用户到localStorage
                    localStorage.setItem('currentUser', JSON.stringify(newUser));

                    // 显示成功通知
                    showNotification('注册成功，即将跳转到首页');

                    // 2秒后跳转到首页
                    setTimeout(function () {
                        window.location.href = 'index.html';
                    }, 2000);
                } else {
                    // 显示错误信息
                    usernameError.textContent = data.message;
                    usernameError.classList.remove('hidden');
                }
            })
            .catch(error => {
                console.error('注册请求出错:', error);
                usernameError.textContent = '注册请求出错，请稍后再试';
                usernameError.classList.remove('hidden');
            });
        }
    });
}

// 初始化密码显示切换
function initPasswordToggle() {
    const toggleLoginPassword = document.getElementById('toggle-login-password');
    const loginPassword = document.getElementById('login-password');

    toggleLoginPassword.addEventListener('click', function () {
        const type = loginPassword.getAttribute('type') === 'password' ? 'text' : 'password';
        loginPassword.setAttribute('type', type);
        toggleLoginPassword.querySelector('i').className = type === 'password' ? 'fas fa-eye-slash text-gray-400' : 'fas fa-eye text-gray-400';
    });

    const toggleRegisterPassword = document.getElementById('toggle-register-password');
    const registerPassword = document.getElementById('register-password');

    toggleRegisterPassword.addEventListener('click', function () {
        const type = registerPassword.getAttribute('type') === 'password' ? 'text' : 'password';
        registerPassword.setAttribute('type', type);
        toggleRegisterPassword.querySelector('i').className = type === 'password' ? 'fas fa-eye-slash text-gray-400' : 'fas fa-eye text-gray-400';
    });

    const toggleRegisterConfirmPassword = document.getElementById('toggle-register-confirm-password');
    const registerConfirmPassword = document.getElementById('register-confirm-password');

    toggleRegisterConfirmPassword.addEventListener('click', function () {
        const type = registerConfirmPassword.getAttribute('type') === 'password' ? 'text' : 'password';
        registerConfirmPassword.setAttribute('type', type);
        toggleRegisterConfirmPassword.querySelector('i').className = type === 'password' ? 'fas fa-eye-slash text-gray-400' : 'fas fa-eye text-gray-400';
    });
}

// 显示通知
function showNotification(message) {
    const notification = document.getElementById('notification');
    notification.textContent = message;
    notification.classList.remove('hidden');
    notification.classList.remove('translate-y-20', 'opacity-0');

    setTimeout(() => {
        notification.classList.add('translate-y-20', 'opacity-0');
        setTimeout(() => {
            notification.classList.add('hidden');
        }, 300);
    }, 2000);
}